package web.filter;

import commons.Constatns;
import pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.IOException;
import java.util.UUID;

@WebFilter(urlPatterns = {"*.do", "*.jsp"})
public class UserLoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String URI = req.getRequestURI();


        if (URI.indexOf("login.do") != -1 || URI.indexOf("login.jsp") != -1 || URI.indexOf("validateCode.do") != -1) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            HttpSession session = req.getSession();
            String uuid = UUID.randomUUID().toString();
            session.setAttribute("told", uuid);
            User user = session  != null ?(User) session.getAttribute(Constatns.User_Session_key):null;

            if (user != null &&session.getAttribute("told") != null) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                req.setAttribute(Constatns.Login_Msg, "访问前需先登录!");
                req.getRequestDispatcher("login.jsp").forward(servletRequest, servletResponse);

            }
        }
    }

    @Override
    public void destroy() {

    }
}
